package cn.edu.scau.cmi.wangmaoren.client.hibenate;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.edu.scau.cmi.wangmaoren.hibernate.dao.MajorDAO;
import cn.edu.scau.cmi.wangmaoren.hibernate.domain.Major;

public class HibernateClient4HibernateSession
{

	public static void main(String[] args)
	{
		Major major = new Major();
		major.setName("信息管理");
		major.setId(4L);

		newMajor(major);
		listMajors();
	}

	public static void newMajor(Major major)
	{
		// (1) 可以复用，因此可以抽取出来；
		// (2) SessionFactory应该单例化；
		Session session = new Configuration().configure().buildSessionFactory().openSession();

		// s session = sf.openSession();
		Transaction transaction = session.beginTransaction();

		// (1) 直接使用Hibernate的CRUD功能
		session.save(major);
		// (2) 也可以将Hibernate的CRUD功能封装为DAO后，调用DAO功能。
		// MajorDAO MajorDAOByHibernate=new MajorDAO();
		// MajorDAOByHibernate.save(Major);
		transaction.commit();
		session.close();
	}

	private static void listMajors()
	{
		MajorDAO MajorDAO = new MajorDAO();
		List Majors = MajorDAO.findAll();
		Iterator<?> MajorIterator = Majors.iterator();
		while (MajorIterator.hasNext())
		{
			Major Major = (Major) MajorIterator.next();
			System.out.println("调用DAO后的专业名是：" + Major.getName() + "，调用DAO后的专业ID号是：" + Major.getId());
		}
	}
}